import { Injectable } from "@nestjs/common";
import { Like, Repository } from "typeorm";
import { Menu } from "./entities/menu.entity";
import { InjectRepository } from "@nestjs/typeorm";


@Injectable()
export class MenuService {
    constructor(
        @InjectRepository(Menu)
        private readonly menuRepository:Repository<Menu>
    ){}
    findAll(query):Promise<Menu[]> {
        // 查找已经激活的菜单(并且想让它按照id的升序进行排序，就不能使用findBy，可以写一个sql)
        // return this.menuRepository.findBy({ active:1 })
        // const sql = `select * from menu where active = 1 order by id asc`
        // return this.menuRepository.query(sql)
        const whereClause:any = {}
        if (query.name) {
            whereClause.name = Like(`%${query.name}%`);
        }
        if (query.active) {
            whereClause.active = query.active;
        }
        
        return this.menuRepository.find({
            order:{
                id:'ASC'
            },
            where: whereClause
        })
    }
    findActive():Promise<Menu[]> {
        return this.menuRepository.find({
            where:{active:1}, // 暂时不需要
            order:{
                id:'ASC'
            }
        })
    }
    findOne(id:number):Promise<Menu | null> {
        return this.menuRepository.findOneBy({ id })
    }
    create(createMenuDto):Promise<Menu> {
        return this.menuRepository.save(createMenuDto)
    }
    update(updateMenuDto) {
        if(updateMenuDto.id) {
            return this.menuRepository.update(updateMenuDto.id,updateMenuDto)
        }
    }
    delete(id:number) {
        return this.menuRepository.delete(id)
    }

}